<script setup>
import { ref, onMounted } from 'vue'
import { listProducts } from '@/services/product'

const products = ref([])

function extractList(payload) {
  if (!payload) return []
  if (Array.isArray(payload)) return payload
  if (Array.isArray(payload.records)) return payload.records
  if (Array.isArray(payload.list)) return payload.list
  if (Array.isArray(payload.items)) return payload.items
  return []
}

onMounted(async () => {
  try {
    const res = await listProducts()
    const list = res?.code === 200 ? extractList(res.data) : []
    products.value = list
    console.log('[Home] products loaded:', products.value?.length)
  } catch (e) {
    console.error('[Home] load products error', e)
    products.value = []
  }
})
</script>

<template>
  <section class="hero card container">
    <div class="hero-banner">超级大促 · 限时抢购</div>
  </section>
  <section class="container">
    <h2>热门推荐</h2>
    <div class="grid grid-4">
      <router-link v-for="p in products" :key="p.id || p.productId" :to="{ name: 'product', params: { id: p.id || p.productId } }" class="card item">
        <div class="thumb">
          <img v-if="p.productImage" :src="p.productImage" alt="" />
        </div>
        <div class="title">{{ p.productName || '' }}</div>
        <div class="price" v-if="p.price !== undefined">￥{{ Number(p.price).toFixed(2) }}</div>
      </router-link>
    </div>
  </section>
</template>

<style scoped>
.hero { height: 180px; margin: 16px auto; display: grid; place-items: center; }
.hero-banner { font-size: 24px; font-weight: 800; color: var(--primary); }
.item { display: block; padding: 12px; }
.thumb { height: 160px; background: #f5f5f5; border-radius: 6px; }
.title { margin-top: 8px; font-size: 14px; }
.price { color: var(--primary); font-weight: 700; margin-top: 4px; }
</style>


